/**
 * @file {piantie目标库job表model}
 */
'use strict'

const {
    DataTypes,
    Model,
    Op
} = require('../../../azeroth').sequelize;
const {
    jobInitData
} = require('../common/init_data');
class JobPiantie extends Model {}

/**
 * @desc 映射需要的字段 【源库的 部分字段 --> 目标库字段】
 */
const initJobData = (sequelize_aim) => {
    JobPiantie.init(
        ...jobInitData, {
            freezeTableName: true,
            sequelize: sequelize_aim,
            modelName: 'job',
            timestamps: false
        }
    )
}

JobPiantie.getMaxJobIdFromSource =  async (sequelize_source) => {
    let sql = 'select max(jobId) as jobId from doff';
    let res = await sequelize_source.query(sql, { type: sequelize_source.QueryTypes.SELECT});
    return res[0].jobId;
}
/**
 * 获取当前的同步uid位置
 * @param {*} sequelize_aim 
 * @returns 
 */
JobPiantie.getLatestJobId = async (sequelize_aim) => {
    let sql = 'select max(uid) as uid from job';
    let res = await sequelize_aim.query(sql, { type: sequelize_aim.QueryTypes.SELECT });
    return res[0].uid;
}
/**
 * get job info by panel_id
 * @param {Sequelize} sequelize_source 
 * @param {String} panel_id / uid
 * @returns 
 */
JobPiantie.getJobInfoByPanelId = async (sequelize_source, queryStr) => {
    console.log(queryStr,'--------------------------------------------------------');
    let query = typeof(queryStr) == 'string' ? `b.uid = (select d.uid from doff d inner join panel_info c on d.uid = c.doff_id where c.panel_id = "${queryStr}")` : `a.uid = ${queryStr}`;
    let query1 = typeof(queryStr) == 'string' ? `(select c.jobId from doff c inner join panel_info d on c.uid = d.doff_id where d.panel_id = "${queryStr}")` : `${queryStr}`;

    let sql = 'select a.uid, a.jobName as job_name, a.doffSum as panel_sum, a.createTime as start_time, a.finishTime as finish_time, a.orderNumber as order_number ' +
        'from job a inner join doff b on a.uid = b.jobId where ' + query;
    let res = await sequelize_source.query(sql, { type: sequelize_source.QueryTypes.SELECT});
    let res1 = await sequelize_source.query('select Count(*) as ok_number from doff where flawCount = 0 and jobId = ' + query1, {
        type: sequelize_source.QueryTypes.SELECT
    });
    return res[0] ? {
        ...res[0],
        ok_number: res1[0].ok_number,
        ng_number: res[0].panel_sum -  res1[0].ok_number
    } : null
}
/**
 * 上传job信息
 * @param {Array} data 上传的缺陷信息数组
 * @returns
 */
JobPiantie.uploadPolInfo = async (data) => {
    let res = await JobPiantie.bulkCreate([{...data}],
        {
        updateOnDuplicate: ['uid', 'job_name', ' panel_sum', ' ok_number', 'ng_number', 'start_time', 'finish_time', 'start_time_str', 'finish_time_str'],
    });
    return res;
}
module.exports = {
    JobPiantie,
    initJobData
};